package gbase

import (
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
	"github.com/hertz-contrib/sse"
)

type PageReq struct {
	Base
	Page  int `json:"page" query:"page"`   //页数
	Limit int `json:"limit" query:"limit"` //每页条数
}

// 只传一个ID参数的请求
type IdReq struct {
	Base
	Id int64 `json:"id" query:"id" vd:"$>0;msg:'id参数缺失'"`
}

// 只传一个ID参数的请求,用于snowflake的ID
type SnowIdReq struct {
	Base
	Id int64 `json:"id,string" query:"id" vd:"$>0;msg:'id参数缺失'"`
}

// params: [data,msg(default:ok)]
func Success(c *app.RequestContext, params ...any) (err error) {
	var (
		msg  string = "ok"
		data any
		//code int = consts.StatusContinue
	)
	for index, param := range params {
		switch index {
		case 0:
			data = param
		case 1:
			msg = param.(string)
		}
	}

	c.JSON(consts.StatusOK, utils.H{
		"code": consts.StatusOK,
		//"status": consts.StatusOK,
		"msg":  msg,
		"data": data,
	})
	return nil
}

func SuccessPage(c *app.RequestContext, count int64, data any, params ...string) (err error) {
	var (
		msg string = "ok"
	)
	if len(params) > 0 {
		msg = params[0]
	}
	c.JSON(consts.StatusOK, utils.H{
		"code": consts.StatusOK,
		//"status": consts.StatusOK,
		"msg":   msg,
		"count": count,
		"data":  data,
	})
	return nil
}

// params [msg(string/error),code(default 100)]
func Fail(c *app.RequestContext, params ...interface{}) (err error) {
	var (
		ok   bool
		msg  string
		code int = consts.StatusContinue
	)
	for index, param := range params {
		switch index {
		case 0:

			if msg, ok = param.(string); !ok {
				msg = param.(error).Error()
			}
		case 1:
			code = param.(int)
		}
	}
	c.JSON(consts.StatusOK, utils.H{
		"code": code,
		//"status": code,
		"msg": msg,
	})
	return nil
}

func SuccessSSE(s *sse.Stream, params ...any) (err error) {
	var (
		msg  string = "ok"
		data any
	)
	for index, param := range params {
		switch index {
		case 0:
			data = param
		case 1:
			msg = param.(string)
		}
	}
	return s.Publish(&sse.Event{
		Event: "success",
		Data: Map{
			"code": consts.StatusOK,
			"msg":  msg,
			"data": data,
		}.ToBytes(),
	})
}

func FailSSE(s *sse.Stream, params ...interface{}) (err error) {
	var (
		ok   bool
		msg  string
		code int = consts.StatusContinue
	)
	for index, param := range params {
		switch index {
		case 0:
			if msg, ok = param.(string); !ok {
				msg = param.(error).Error()
			}
		case 1:
			code = param.(int)
		}
	}
	return s.Publish(&sse.Event{
		Event: "fail",
		Data: Map{
			"code": code,
			"msg":  msg,
		}.ToBytes(),
	})
}
